﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Core.Service;
using System.Threading;
using Icms.Data;

namespace Icms.Service
{
    public class ReportService : IReportService
    {
        private readonly IReportRepo reportRepo;
        private readonly IReportBuilder reportBuilder;
        private readonly IRepo<ReportRequest> reportRequest;

        public ReportService(IReportBuilder reportBuilder, IRepo<ReportRequest> reportRequest)
        {
            this.reportRequest = new Repo<ReportRequest>(new DbContextFactory());
            reportRepo = new ReportRepo(new ConnectionFactory());
            this.reportBuilder = reportBuilder;
            this.reportRequest = reportRequest;
        }

        private void RequestReport(Guid requestId)
        {
            try
            {
                using (var db = new Db())
                {
                    var request = db.Set<ReportRequest>().Find(requestId);
                    var parameters = new Dictionary<string, object>
                                         {
                                             {"DateFrom", request.DateFrom},
                                             {"DateTo", request.DateTo},
                                         };
                    if (request.CourtId.HasValue) parameters.Add("Court_Id", request.CourtId);
                    var data = reportRepo.GetData(request.ReportTemplate.Name, parameters);
                    var court = db.Courts.Find(request.CourtId);
                    var t = court != null ? court.Title : "toate";
                    request.FileName = reportBuilder.BuildReport(data,
                                                                 request.ReportTemplate.Name, request.DateFrom,
                                                                 request.DateTo, t);

                    db.Set<Message>().Add(new Message
                                              {
                                                  RecipientId = request.UserId,
                                                  DateSent = DateTime.Now,
                                                  Subject = "raport " + request.ReportTemplate.Title,
                                                  Text = "raportul cerut de dvs. a fost procesat cu succes"
                                              });
                    db.SaveChanges();
                }
            }
            catch(Exception ex)
            {
                using (var db = new Db())
                {
                    var rr = db.ReportRequests.Find(requestId);
                    rr.FileName = "error";
                    db.Set<Message>().Add(new Message
                    {
                        RecipientId = rr.UserId,
                        DateSent = DateTime.Now,
                        Subject = "raport " + rr.ReportTemplate.Title,
                        Text = "a aparut o eroare in timpul procesarii raportului cerut de dvs. Mesaj eroare:"+ex.Message
                    });
                    db.SaveChanges();
                    throw;
                }
            }
        }

        public Guid Create(ReportRequest e, Guid userId)
        {
            e.Date = DateTime.Now;
            e.UserId = userId;
            reportRequest.Insert(e);
            reportRequest.Save();
            ThreadPool.QueueUserWorkItem(s => RequestReport(e.Id));
            return e.Id;
        }

        public string GetFilePath(Guid id)
        {
            return ConfigurationManager.AppSettings["storagePath"] + @"\RequestedReports\" + reportRequest.Get(id).FileName + ".xls";
        }
    }
}